package com.itheima.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.Result;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.PageQuery;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.enums.UserStatus;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements IUserService  {

    /**
     * 根据id扣减余额
     * @param id
     * @param money
     * @return
     */
    @Transactional
    @Override
    public void deductionMoneyById(Long id, Integer money) {
        //查询用户
        User user = this.getById(id);
        //校验用户状态
        if (user == null || user.getStatus() == UserStatus.FROZEN){
            throw new RuntimeException("用户状态异常");
        }

        //校验余额是否充足
        if (user.getBalance() < money){
            throw new RuntimeException("用户余额不足");
        }
        //扣减余额  update tb_user set balance = balance - ?
        //user.setBalance(user.getBalance() - money);
        //this.updateById(user);
        int remainBalance = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance, remainBalance)
                .set(remainBalance == 0,User::getStatus, 2)
                .eq(User::getId, id)
                .eq(User::getBalance,user.getBalance())//乐观锁 修改前再次检查前后查询出的余额是否没有变化
                .update();//执行update方法

        //baseMapper.deductBalance(id,money);
    }

    /**
     * 复杂条件查询
     *
     * @param name
     * @param status
     * @param minBalance
     * @param maxBalance
     * @return
     */
    @Override
    public List<User> queryUsers(String name, Integer status, Integer minBalance, Integer maxBalance) {
        List<User> list = lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .gt(minBalance != null, User::getBalance, minBalance)
                .lt(maxBalance != null, User::getBalance, maxBalance)
                .list();

        return list;
    }

    /**
     * 根据id查询用户信息
     * @param id
     * @return
     */
    @Override
    public UserVO queryUserAndAddressById(Long id) {
        //1查询用户
        User user = getById(id);
        if (user == null || user.getStatus() == UserStatus.FROZEN){
            throw new RuntimeException("用户状态异常");
        }
        //2查询地址
        List<Address> list = Db.lambdaQuery(Address.class)
                .eq(Address::getUserId, id)
                .list();
        //转USer的PO为VO
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);

        //转地址VO
        if (CollUtil.isNotEmpty(list)){
            userVO.setAddresses(BeanUtil.copyToList(list, AddressVO.class));
        }
        return userVO;
    }

    /**
     * 根据ids批量查询用户
     * @param ids
     * @return
     */
    @Override
    public List<UserVO> queryUserAndAddressByIds(List<Long> ids) {
        //查询用户
        List<User> users = listByIds(ids);
        //判断
        if (CollUtil.isEmpty(users)){
            return Collections.emptyList();
        }

        List<UserVO> userVOS = new ArrayList<>();
        for (User user : users) {
            List<Address> list = Db.lambdaQuery(Address.class)
                    .eq(Address::getUserId, user.getId())
                    .list();

            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            if (CollUtil.isNotEmpty(list)){
                userVO.setAddresses(BeanUtil.copyToList(list, AddressVO.class));
            }
            userVOS.add(userVO);
        }
        return userVOS;



        /*//查询地址
        //获取用户id集合
        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());
        List<Address> address = Db.lambdaQuery(Address.class)
                .in(Address::getUserId, userIds)
                .list();
        List<AddressVO> addressVOList = BeanUtil.copyToList(address, AddressVO.class);
        //梳理地址集合,分类整理,相同用户放一个集合.对用户地址集合分组
        //key是用户id,值是对应地址集合
        Map<Long, List<AddressVO>> addressMap = new HashMap<>(0);
        if (CollUtil.isNotEmpty(addressVOList)){
            addressMap = addressVOList.stream().collect(Collectors.groupingBy(AddressVO::getUserId));

        }
        //转VO返回
        List<UserVO> list = new ArrayList<>(users.size());
        for (User user : users) {
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            userVO.setAddresses(addressMap.get(user.getId()));
            list.add(userVO);
        }
        return list;*/
    }

    /**
     * 分页查询
     *
     * @param userQuery
     * @return
     */
    @Override
    public Result<PageDTO<UserVO>> queryUsersPage(UserQuery userQuery) {
        String name = userQuery.getName();
        UserStatus status = userQuery.getStatus();
        //构建分页条件
        Page<User> page = userQuery.toMpPageDefaultSortByUpdateTimeDesc();
        //构建查询条件
        lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .page(page);
        //总页数和总条数

        return Result.success(PageDTO.of(page, UserVO.class));
    }
}
